import { Material, Mesh, Object3D, Texture } from 'three';
import { Command } from '../command.js';
import { Editor } from '../editor.js';

/**
 * @param editor Editor
 * @param object THREE.Object3D
 * @param mapName string
 * @param newMap THREE.Texture
 * @constructor
 */
class SetMaterialMapCommand<K extends keyof Material> extends Command {

	object:Mesh;
	material:Material;
	oldMap:Texture|undefined;
	newMap:Texture;
	mapName:K;
	constructor( editor:Editor, object:Object3D, mapName:K, newMap:Texture, materialSlot:number ) {

		super( editor );

		this.type = 'SetMaterialMapCommand';
		this.name = `Set Material.${mapName}`;

		this.object = object as Mesh;
		this.material = this.editor.getObjectMaterial( this.object, materialSlot );

		this.oldMap = ( object !== undefined ) ? this.material[ mapName ] : undefined;
		this.newMap = newMap;

		this.mapName = mapName;

	}

	execute() {

		if ( this.oldMap !== null && this.oldMap !== undefined ) this.oldMap.dispose();

		(this.material[ this.mapName ] as Texture) = this.newMap;
		this.material.needsUpdate = true;

		this.editor.signals.materialChanged.dispatch( this.material );

	}

	undo() {
		if(this.oldMap)
		(this.material[ this.mapName ] as Texture) = this.oldMap;
		this.material.needsUpdate = true;

		this.editor.signals.materialChanged.dispatch( this.material );

	}


}

export { SetMaterialMapCommand };
